package com.caocaog.market.utils;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.RedisUtil;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.*;

import static org.jeecg.common.constant.CacheConstant.*;

/**
 * 餐号工具类
 *
 * @author chechen
 * @date 2022-10-26
 */
@Slf4j
@Component
@EnableScheduling
public class MealNumberUtil {

    @Setter(onMethod_ = @Autowired)
    private RedisUtil redisUtil;


    /**
     * 根据店铺id获取餐号
     *
     * @param shopId  店铺id
     * @param orderId 订单id
     * @return 餐号
     */
    public int getMealNumber(String shopId, String orderId) {
        return getMealNumber(shopId, orderId, new Date());
    }

    public int getMealNumber(String shopId, String orderId, Date date) {
        Assert.notNull(shopId, "ShopId must not be null!");
        Assert.notNull(orderId, "OrderId must not be null!");
        Assert.notNull(date, "Date must not be null!");

        SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
        if (!sdf.format(new Date()).equals(sdf.format(date))) { // 判断是否是今天，不是则 return 0
            return 0;
        }

        Integer mealNumberByOrderId = (Integer) redisUtil.get(build(ORDER_MEAL_NUMBER, orderId));
        if (Objects.nonNull(mealNumberByOrderId)) return mealNumberByOrderId;

        // else 此 orderId 未有餐号👇

        // 获取当前店铺餐号
        Integer currentMealNumber = (Integer) Optional.ofNullable(redisUtil.get(build(SHOP_MEAL_NUMBER, shopId))).orElse(0);

        redisUtil.set(build(ORDER_MEAL_NUMBER, orderId), ++currentMealNumber);
        redisUtil.set(build(SHOP_MEAL_NUMBER, shopId), currentMealNumber);
        return currentMealNumber;

    }


    /**
     * 每天0点清除餐号缓存数据
     *
     * @throws JobExecutionException 任务执行异常
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void execute() throws JobExecutionException {
        log.info("清除餐号缓存数据");

        Set<String> keys = redisUtil.scan("mealNumber");
        if (keys.isEmpty()) return;

        String[] keyArray = keys.toArray(new String[0]);
        redisUtil.del(keyArray);

        log.info("清除餐号缓存数据-> " + Arrays.toString(keyArray));
    }

}
